package com.xneure.utils.bean;

import java.util.Date;

/**
 * <p>
 * 日期计算工具
 * </p>
 *
 * <p>
 * Copyright: 版权所有<br>
 *
 * @author 张军
 * @version 2016年4月17日
 * 
 *          用于计算两个时间的差值
 */
public class DateDiff {
	public enum DiffType {
		DATY, HOUR, MIN, SECOND;
	}

	static long _s = 1;
	static long _min = _s * 60;
	static long _hour = _min * 60;
	static long _day = _hour * 24;
	private int daty;
	private int hour;
	private int min;
	private int second;
	private boolean before = true;

	/**
	 * 日期不分先后只计算差值
	 * 
	 * @param now
	 * @param date
	 */
	public DateDiff(Date now, Date date) {
		int compareTo = now.compareTo(date);
		if (compareTo == 1) {
			statistics(now.getTime() - date.getTime());
			before = true;
		} else if (compareTo == -1) {
			statistics(date.getTime() - now.getTime());
			before = false;
		}
	}

	public boolean isBefore() {
		return before;
	}

	/**
	 * @param time
	 *            处理后的日期差值
	 */
	public DateDiff(long time) {
		statistics(time);
	}

	public void statistics(long time) {
		time /= 1000;
		if (time >= _day) {
			daty = (int) (time / _day);
			time -= _day * daty;
		}
		if (time >= _hour) {
			hour = (int) (time / _hour);
			time -= _hour * hour;
		}
		if (time >= _min) {
			min = (int) (time / _min);
			time -= _min * min;
		}
		if (time >= _s) {
			second = (int) time;
		}
	}

	/**
	 * 判断时间差是否大于目标值
	 * 
	 * @param dt
	 *            目标类型
	 * @param val
	 *            目标值
	 * @return boolean
	 */
	public boolean isBeyond(DiffType dt, int val) {
		switch (dt) {
		case DATY:
			return daty > val || daty == val && (hour > 0 || min > 0 || second > 0);
		case HOUR:
			return hour > val || hour == val && (daty > 0 || min > 0 || second > 0);
		case MIN:
			return min > val || min == val && (daty > 0 || hour > 0 || second > 0);
		case SECOND:
			return second > val || second == val && (daty > 0 || hour > 0 || min > 0);
		default:
			return false;
		}
	}

	public int getDaty() {
		return daty;
	}

	public int getHour() {
		return hour;
	}

	public int getMin() {
		return min;
	}

	public int getSecond() {
		return second;
	}

	public boolean isDifference() {
		return daty > 0 && hour > 0 && min > 0 && second > 0;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		if (daty > 0) {
			sb.append(daty).append(" 天\r\n");
		}
		if (hour > 0) {
			sb.append(hour).append(" 小时\r\n");
		}
		if (min > 0) {
			sb.append(min).append(" 分钟\r\n");
		}
		if (second > 0) {
			sb.append(second).append(" 秒\r\n");
		}
		return sb.toString();
	}
}
